var histogram;
var pieChart;
var allNames = [];
var allNums = [];
var allObj = [];
var total=0;
var params={
    start:0,
    limit:10,
    search: 123223,
    startDate: 0,
    endDate: 0
};
$(function () {
    initDateRangePicker();
    initHistogram();
    initPieChart();
    loadOption();
});

function initDateRangePicker() {
    var date = new Date();
    if(date.getMonth() > 0) {
        $('input[name="daterange"]').daterangepicker({
                locale: {
                    format: 'YYYY-MM-DD'
                },
                startDate: date.getFullYear() + "-" + formNumber(date.getMonth()) + formNumber(date.getDate()),
                endDate: date.getFullYear() + "-" + formNumber(date.getMonth() + 1) + '-' + formNumber(date.getDate())
            },
            function (start, end, label) {
                //                        alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
            });
    } else {
        $('input[name="daterange"]').daterangepicker({
                locale: {
                    format: 'YYYY-MM-DD'
                },
                startDate: date.getFullYear() - 1 + "-" + formNumber(date.getMonth() + 12) + formNumber(date.getDate()),
                endDate: date.getFullYear() + "-" + formNumber(date.getMonth() + 1) + '-' + formNumber(date.getDate())
            },
            function (start, end, label) {
                //                        alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
            });
    }
}

function clearSelect() {
    var region = $("#region");
    var select = $(".select2-selection__rendered");
    region.find("option:first").prop("selected", 'selected');
    select.text(region.find("option:first").text());
    select.attr("title", region.find("option:first").text());
    initDateRangePicker();
    loadHistogramData();
}

/**
 * 加载地区下拉框数据
 */
function loadOption() {
    var url = baseRegionUrl + "list/region?start=0&limit=1000000";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "GET",
        contentType: "application/json",
        success: function (data) {
            var arr = [];
            $(data.data.rows).each(function (index, obj) {
                var region = {"id": obj.id, "text": obj.name};
                arr.push(region);
            });
            $('#region').select2({
                data: arr
            });
            loadHistogramData();
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}

/**
 * 加载分页数据
 */
function loadPage() {
    var pageSelect = $("#page");
    pageSelect.empty();
    var page = total / 10;
    if ($("#page").val() === 0 || !$("#page").val()) {
        for (var i = 0; i < page; i++) {
            var text = (i * 10 + 1) + "-" + ((i + 1) * 10);
            if (i === 0) {
                pageSelect.append("<option selected value='" + i + "'>" + text + "</option>");
            } else {
                pageSelect.append("<option value='" + i + "'>" + text + "</option>");
            }
        }
    }
}
// function loadPage() {
//     var pageSelect = $("#page");
//     pageSelect.empty();
//     var page = allNames.length / 10;
//     for (var i = 0; i < page + 1; i++) {
//         var text = (i + 1) + "-" + (i + 10);
//         if (i === 0) {
//             pageSelect.append("<option selected>" + text + "</option>");
//         } else {
//             pageSelect.append("<option>" + text + "</option>");
//         }
//     }
// }

/**
 * 加载总数据
 */
function loadHistogramData(type) {
    allObj=[];
    var dateInterval = $("#reservation").val().split(" - ");
    var startDate = Date.parse(dateInterval[0]);
    var endDate = Date.parse(dateInterval[1]);
    var url = baseQuestionUrl + "list/shortroad";
    params.search=$("#region").val();
    params.startDate=startDate;
    params.endDate=endDate;

    ajaxCommon.request('get',url,params,function (data) {
        allNames.splice(0, allNames.length);
        allNums.splice(0, allNums.length);
        total=data.data.total;
        if (!type) {
            loadPage();
        }
        $(data.data.rows).each(function (index, obj) {
            allNames.push(obj.firest);
            allNums.push(obj.count);
            allObj.push(obj)
        });
        // 将数据载入柱状图
        loadHistogram(0);
        // 将数据载入表格
        loadTable(0);
        // 将数据载入饼图
        loadPieData(allNames[0]);

        var url1 = baseQuestionUrl + 'list/beforekey';
        ajaxCommon.request('get',url1,params,function (data1) {
            allObj.map(function(obj, index){
                if (obj.second === undefined) {
                    obj.second = ''
                }
                if (obj.secCount === undefined) {
                    obj.secCount = 0
                }
                data1.data.rows.map(function(obj1, index1){
                    if (obj.firest === obj1.second) {
                        obj.second = obj1.first?obj1.first:'--';
                        obj.secCount = obj1.count;
                    }
                });
                return obj;
            });
            loadPieTable();
        });
    });
}

/**
 * 加载表格数据
 * @param startIndex
 */
function loadTable(startIndex) {
    var keyword = $("#keyword");
    var num = $("#num");
    keyword.empty();
    num.empty();
    keyword.append("<td>关键词</td>");
    num.append("<td>次数</td>");
    var index;
    if (startIndex + 10 < allNames.length && startIndex + 10 < allNums.length) {
        index = startIndex + 10;
    } else {
        index = allNames.length;
    }
    for (var i = startIndex; i < index; i++) {
        var keywordTd = "<td>" + allNames[i] + "</td>";
        var numTd = "<td>" + allNums[i] + "</td>";
        keyword.append($(keywordTd));
        num.append($(numTd));
    }
}

/**
 * 初始化柱状图
 */
function initHistogram() {
    var option = {
        title: {
            text: '数量统计',
            left: 50
        },
        color: ['#3398DB'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                // data: ['价格', '安全', '优惠', '配置', '外形', '舒适', '油耗', '活动', '内饰', '保养'],
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    rotate: 20
                },
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '次数',
                type: 'bar',
                barWidth: '60%'/*,
                data: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]*/
            }
        ]
    };
    histogram = echarts.init(document.getElementById("histogram"));
    histogram.setOption(option);
    histogram.on('click', function (params) {
        // loadPieData(params.name);
    });
}

/**
 * 根据分组索引来加载柱状图
 * @param startIndex
 */
function loadHistogram(startIndex) {
    var names = [];
    var nums = [];
    var index;
    if (startIndex + 10 < allNames.length) {
        index = startIndex + 10;
    } else {
        index = allNames.length;
    }
    for (var i = startIndex; i < index; i++) {
        names.push(allNames[i]);
        nums.push(allNums[i]);
    }
    histogram.setOption({
        xAxis: {
            data: names
        },
        series: [{
            name: '次数',
            data: nums
        }]
    });

    // 饼图数据加载
    var pieArray = [];
    var sum=0;
    for (var i = 0; i < allNames.length; i++) {
        var pieData = {"value": allNums[i], "name": allNames[i]};
        pieArray.push(pieData);
        sum+=allNums[i]
    }
    pieChart.setOption({
        title: {
            subtext: sum
        },
        // legend: {
        //     orient: 'vertical',
        //     x: 'right',
        //     y: 'middle',
        //     itemWidth: 10,
        //     itemHeight: 10,
        //     align: 'left',
        //     textStyle: {
        //         fontSize: 16,
        //         color: '#5a5a5a',
        //         lineHeight: 35
        //     },
        //     data:allNames,
        // },
        series: [{
            radius: ['50%', '70%'],
            data: pieArray,
        }]
    });

}

function loadPieTable(){
    var str='';
    var color = ['#37a5ff','#4fcb74','#FBD438','#f04664','#9860E5','#37CBCB', '#37a5ff','#4fcb74','#FBD438','#f04664']
    allObj.map(function(obj, index){
        str+='<li style="display: flex;">' +
            '<span style="line-height: 28px;width: 10px;height: 10px;border-radius: 2px;background: '+color[index]+';margin: 9px 10px 0 0;"></span>' +
            '<span style="flex: 3;font-size: 16px;line-height: 28px;color: #5a5a5a;">'+obj.firest+'</span>' +
            '<span style="flex: 1;font-size: 16px;line-height: 28px;color: #E9E9E9;">|</span>' +
            '<span style="flex: 3;font-size: 16px;line-height: 28px;color: #6a6a6a;">'+obj.second+'</span>' +
            '<span style="flex: 1;font-size: 16px;line-height: 28px;color: #5a5a5a;text-align: center;">'+obj.secCount+'</span>' +
            '</li>'
    });
    $('#pieTable').html(str)
}

/**
 * 根据keyword去加载饼图
 * @param keyword
 */
function loadPieData(keyword) {
    // var regionId = $("#region").val();
    // var dateInterval = $("#reservation").val().split(" - ");
    // var startDate = Date.parse(dateInterval[0]);
    // var endDate = Date.parse(dateInterval[1]);
    // var url = baseStatisticalUrl + "query/moreKeyWordMatch?start=0&limit=1000000";
    // $.ajax(ajaxCommon.buildLoadingOption({
    //     url: url,
    //     headers: {
    //         "authorization": 'Bearer ' + getCookie(cookieName)
    //     },
    //     data: JSON.stringify({"keyword": keyword, "regionId": regionId, "startDate": startDate, "endDate": endDate}),
    //     type: "POST",
    //     contentType: "application/json",
    //     success: function (data) {
    //         // 将数据载入饼图
    //         var pieArray = [];
    //         for (var i = 0; i < data.data.keyword.length; i++) {
    //             var pieData = {"value": data.data.num[i], "name": data.data.keyword[i]};
    //             pieArray.push(pieData);
    //         }
    //     },
    //     error: function (request, error) {
    //         if (request.status === 401) {
    //             $(location).attr('href', 'login.html');
    //         } else {
    //             swal("失败");
    //         }
    //     }
    // }));
}

/**
 * 初始化饼图
 */
function initPieChart() {
    var option = {
        title: {
            text: '总提问次数',
            textStyle: {
                fontWeight: 'normal',
                color: '#aaa',
                fontSize: 16
            },
            subtext: '0',
            subtextStyle: {
                fontWeight: 'normal',
                color: '#333',
                fontSize: 22
            },
            x: 'center',
            y: '45%'
        },
        color: ['#37a5ff','#4fcb74','#FBD438','#f04664','#9860E5','#37CBCB'],
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        series: [
            {
                name: '客户还对这些方面感兴趣',
                type: 'pie',
                center: ['50%', '50%'],
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    pieChart = echarts.init(document.getElementById("pieChart"));
    pieChart.setOption(option);
}

/**
 * 分页选择框的选择时间处理
 */
function indexChange() {
    var index = $("#page").val().split("-")[0];
    loadHistogram(index);
    loadTable(index);
    loadPieData(allNames[index]);
}

/**
 * 导出Excel
 */
function exportExcel() {
    if (allNames.length <= 0) {
        swal("当前数据为空");
        return;
    }
    var sheetData = [];
    $(allObj).each(function (index, obj) {
        var d = {
            "rank": index + 1,
            "keyword": obj.firest,
            "number": obj.count,
            'next': obj.second,
            'count': obj.secCount
        };
        sheetData.push(d);
    });
    var option = {};
    option.fileName = "常匹配关键字(" + $("#reservation").val().split(" - ") + ")";
    option.datas = [
        {
            sheetData: sheetData,
            sheetName: 'matchQuestion',
            sheetFilter: ['rank', 'keyword', "number", 'next', 'count'],
            sheetHeader: ['排名', '关键字', '次数', '下一关键字', '次数']
        },
        {
            sheetData: sheetData
        }
    ];
    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
}

/**
 * 切换分页
 */
function changePage() {
    params.start=$('#page').val()*10;
    loadHistogramData(params.start);
    loadPieTable(params.start);
}
